import http from "../../../utils/https";
// 获取基础URL
const baseURL = 'http://localhost:8080/';

   // service/pages/addHouse/addHouse.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 当前步骤
    currentStep: 0,
    
    // 是否认证失败
    isFailed: true,
    
    // 失败原因
    failReason: '身份证信息与业主信息不符，请确认您的身份证信息是否正确，或联系物业确认业主信息。',
    
    // 信息表单数据
    formData: {
      houseId:0,
      community:'',
      communityId: 0,
      building:'',
      buildingId: 0,
      houseNumber: '',
      status: '自住',
      isDefault: false,
      houseStatusName:'',
      houseStatusId:0
    },
    
    // 图片上传相关
    imagePaths: [], // 存储临时图片路径
    imageUrls: [], // 存储上传后的图片URL
    maxImageCount: 5, // 最大上传图片数量
    //存储返回的url
    image:[],
    //转为字符串
    imageUrl:'',
    
    // 住户信息表单数据
    residentData: {
      id:0,
      residentName: '',
      gender: '0',
      idTypeName: '',
      idCardTypeId:0,
      idNumber: '',
      relation: '',
      relationToOwnerId:0,
      phoneNumber: '',
      verifyCode: '123456',
    },
    communityList:[],
    buildingList:[],
    houseStatus:[],
    houseList:[],
    idTypeList:[],
    relationList:[],

    //业主

    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 如果有传入的参数，可以根据参数设置是否显示失败界面
    if (options.showFailed) {
      this.setData({
        isFailed: options.showFailed === 'true'
      });
    }
    this.setData({
      'residentData.id':wx.getStorageSync('residentId')
    })
    console.log(wx.getStorageSync('residentId'));
    console.log(this.data.residentData.id);
    this.queryCommunity();
    this.queryHouseStatus();
    this.queryIdType();
    this.queryRelation();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 第一步：房屋信息相关方法
  // 选择小区
  selectCommunity() {
    const communityList=this.data.communityList
    console.log(communityList);
    wx.showActionSheet({
      itemList: communityList.map(item=>item.communityName) || '暂无小区',
      success: (res) => {
        const selectedItem = communityList[res.tapIndex];
        console.log("idid",selectedItem.id );
        this.setData({
        'formData.community': selectedItem.communityName,
        'formData.communityId': selectedItem.id 
        });
      }
    });
  },

  // 选择楼栋
  selectBuilding() {

  // 先检查是否已选择小区
  if (!this.data.formData.communityId) {
    wx.showToast({
      title: '请先选择小区',
      icon: 'none'
    });
    return;
  }


    wx.showLoading({
      title: '加载中...'
    });


    http.get('building/building/list',{
    communityId:this.data.formData.communityId
  })
  .then(resp=>{
    wx.hideLoading();
    this.setData({
      buildingList:resp.rows
    })


    if (resp.rows && resp.rows.length > 0) {
    const buildingList = this.data.buildingList
    console.log("房屋",buildingList);
    wx.showActionSheet({
      itemList: buildingList.map(item=>item.buildingName),
      success: (res) => {
        const selectedItem = buildingList[res.tapIndex];
        this.setData({
          'formData.building': selectedItem.buildingName,
          'formData.buildingId':selectedItem.id
        });
      }
    });
    }else {
      wx.showToast({
        title: '该小区暂无楼栋信息',
        icon: 'none'
      });
    }
  })
  .catch(err=>{
    console.log("请求失败",err);
    wx.showToast({
      title: '获取楼栋失败',
      icon: 'none'
    });
  })
  },



  // 选择房屋
  selectHouse() {
    // 先检查是否已选择小区和楼栋
    if (!this.data.formData.communityId) {
      wx.showToast({
        title: '请先选择小区',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.formData.buildingId) {
      wx.showToast({
        title: '请先选择楼栋',
        icon: 'none'
      });
      return;
    }
    // 显示加载中
    wx.showLoading({
      title: '加载中...'
    });
    
    // 查询房屋
    http.get('house/house/list', {
      communityId: this.data.formData.communityId,
      buildingBlockId: this.data.formData.buildingId
    })
    .then(resp => {
      wx.hideLoading();
      this.setData({
        houseList:resp.rows
      })


      if (resp.rows && resp.rows.length > 0) {
        
        const houseList=resp.rows
        
        wx.showActionSheet({
          itemList: houseList.map(item=>item.houseNumber),
          success: (res) => {
            const selectedHouse = houseList[res.tapIndex];
            this.setData({
              'formData.houseNumber': selectedHouse.houseNumber,
              'formData.houseId': selectedHouse.id
            });
          }
        });
      } else {
        wx.showToast({
          title: '该楼栋暂无房屋信息',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      wx.hideLoading();
      console.log("请求失败", err);
      wx.showToast({
        title: '获取房屋失败',
        icon: 'none'
      });
    });
  },
  
  // 上传房屋照片
  uploadHousePhoto() {
    const remainingCount = this.data.maxImageCount - this.data.imagePaths.length;
    if (remainingCount <= 0) {
      wx.showToast({
        title: '最多上传5张图片',
        icon: 'none'
      });
      return;
    }
    
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log("resp：",res);
        // 保存临时图片路径
        const newImagePaths = this.data.imagePaths.concat(res.tempFilePaths);    
        this.setData({
          imagePaths:newImagePaths
        })
        // 上传图片到服务器
        this.uploadImages(res.tempFilePaths);
      }
    });
  },
  
  // 上传图片到服务器
  uploadImages(tempFilePaths) {
    if (!tempFilePaths || tempFilePaths.length === 0) return;
    console.log("图片",this.data.imagePaths);
    
    wx.showLoading({
      title: '上传中...',
      mask: true
    });
    
    const that = this; // 保存this引用
    let uploadedCount = 0;
    const totalFiles = tempFilePaths.length;
    
    for (let index = 0; index < tempFilePaths.length; index++) {
      wx.uploadFile({
        filePath: tempFilePaths[index],
        name: 'file',
        url: 'http://localhost:8080/common/upload',
        header:{
          'Authorization':wx.getStorageSync('token')
        },
        success(uploadRes) {
          console.log('上传成功', uploadRes.data);
          // 解析返回的JSON字符串
          const result = JSON.parse(uploadRes.data);
          if(result.code==200){
            // 使用保存的that引用而不是this
            that.setData({
              image: that.data.image.concat(result.url)
            });
          }
          
          // 计数上传完成的文件
          uploadedCount++;
          
          // 当所有文件都上传完成时，更新imageUrl并隐藏加载提示
          if(uploadedCount === totalFiles) {
            that.setData({
              imageUrl: that.data.image.join()
            });
            wx.hideLoading();
          }
        },
        fail(err) {
          console.error('上传失败', err);
          uploadedCount++;
          
          if(uploadedCount === totalFiles) {
            that.setData({
              imageUrl: that.data.image.join()
            });
            wx.hideLoading();
          }
        }
      });
    }
  },
  
  // 预览房屋照片
  previewHousePhoto(e) {
    const index = e.currentTarget.dataset.index;
    const urls = this.data.imagePaths.length > 0 ? this.data.imagePaths : this.data.imageUrls;
    
    wx.previewImage({
      current: urls[index], // 当前显示图片的链接
      urls: urls // 需要预览的图片链接列表
    });
  },
  
  // 删除房屋照片
  deleteHousePhoto(e) {
    const index = e.currentTarget.dataset.index;
    const imagePaths = [...this.data.imagePaths];
    const imageUrls = [...this.data.imageUrls];
    
    // 删除对应索引的图片
    if (index < imagePaths.length) {
      imagePaths.splice(index, 1);
    }
    
    if (index < imageUrls.length) {
      imageUrls.splice(index, 1);
    }
    
    this.setData({
      imagePaths: imagePaths,
      imageUrls: imageUrls,
      'formData.housePhotos': imageUrls
    });
  },
  
  // 预览房屋照片
  previewHousePhoto(e) {
    const index = e.currentTarget.dataset.index;
    const urls = this.data.imagePaths.length > 0 ? this.data.imagePaths : this.data.imageUrls;
    
    wx.previewImage({
      current: urls[index], // 当前显示图片的链接
      urls: urls // 需要预览的图片链接列表
    });
  },
  
  // 删除房屋照片
  deleteHousePhoto(e) {
    const index = e.currentTarget.dataset.index;
    const imagePaths = [...this.data.imagePaths];
    const imageUrls = [...this.data.imageUrls];
    
    // 删除对应索引的图片
    if (index < imagePaths.length) {
      imagePaths.splice(index, 1);
    }
    
    if (index < imageUrls.length) {
      imageUrls.splice(index, 1);
    }
    
    this.setData({
      imagePaths: imagePaths,
      imageUrls: imageUrls,
      'formData.housePhotos': imageUrls
    });
  },

  // 选择房屋状态
  selectStatus() {
    const houseStatusList=this.data.houseStatus
    wx.showActionSheet({
      itemList: houseStatusList.map(item=>item.statusName),
      success: (res) => {
        const selectedItem = houseStatusList[res.tapIndex];
        this.setData({
          'formData.houseStatusName': selectedItem.statusName,
          'formData.houseStatusId':selectedItem.id
        });
      }
    });
  },

  // 设置默认房屋
  setDefaultHouse(e) {
    this.setData({
      'formData.isDefault': e.detail.value
    });
  },


  // 第二步：住户信息相关方法
  // 输入住户姓名
  inputTenantName(e) {
    this.setData({
      'residentData.residentName': e.detail.value
    });
  },

  // 选择性别
  selectGender(e) {
    this.setData({
      'residentData.gender': e.currentTarget.dataset.gender
    });
  },

  // 选择证件类型
  selectIdType() {
    const idTypeList = this.data.idTypeList
    wx.showActionSheet({
      itemList: idTypeList.map(item=>item.typeName),
      success: (res) => {
        const selectedItem=idTypeList[res.tapIndex]
        this.setData({
          'residentData.idTypeName': selectedItem.typeName,
          'residentData.idCardTypeId':selectedItem.id
        });
      }
    });
  },

  // 输入证件号码
  inputIdNumber(e) {
    this.setData({
      'residentData.idNumber': e.detail.value
    });
  },

  // 选择与业主关系
  selectRelation() {
    const relationList=this.data.relationList
    wx.showActionSheet({
      itemList: relationList.map(item=>item.relationName),
      success: (res) => {
        const selectedItem=relationList[res.tapIndex]
        this.setData({
          'residentData.relation': selectedItem.relationName,
          'residentData.relationToOwnerId': selectedItem.id
        });

        console.log("this",this.data.residentData.relationToOwnerId);
      }
    });
  },

  // 输入手机号码
  inputPhone(e) {
    this.setData({
      'residentData.phoneNumber': e.detail.value
    });
  },

  // 发送验证码
  sendVerifyCode() {
    if (!this.data.residentData.phoneNumber) {
      wx.showToast({
        title: '请先输入手机号码',
        icon: 'none'
      });
      return;
    }
    
    // 模拟发送验证码
    wx.showToast({
      title: '验证码已发送',
      icon: 'success'
    });
  },

  // 输入验证码
  inputVerifyCode(e) {
    this.setData({
      'tenantData.verifyCode': e.detail.value
    });
  },

  // 下一步
  nextStep() {
    if (this.data.currentStep === 0) {
      // 验证第一步表单
      const { community, building, houseNumber, status } = this.data.formData;
      if (!community || !building || !houseNumber || !status) {
        wx.showToast({
          title: '请填写完整房屋信息',
          icon: 'none'
        });
        console.log("表单数据",this.data.formData);
        return;
      }
      
      if (!this.data.imagePaths || this.data.imagePaths.length === 0) {
        wx.showToast({
          title: '请上传房屋照片',
          icon: 'none'
        });
        return;
      }
      
      // 进入第二步
      this.setData({
        currentStep: 1
      });
    } else if (this.data.currentStep === 1) {
      // 验证第二步表单
      const { residentName, idTypeName, idNumber, relation, phoneNumber, verifyCode } = this.data.residentData;
      if (!residentName) {
        wx.showToast({
          title: '请输入住户姓名',
          icon: 'none'
        });
        return;
      }
      if (!idTypeName) {
        wx.showToast({
          title: '请选择证件类型',
          icon: 'none'
        });
        return;
      }
      if (!idNumber||idNumber.length !=18) {
        wx.showToast({
          title: '证件号码为空或者不满18位',
          icon: 'none'
        });
        return;
      }
      if (!relation) {
        wx.showToast({
          title: '请选择与业主关系',
          icon: 'none'
        });
        return;
      }
      if (!phoneNumber || phoneNumber.length!=11) {
        wx.showToast({
          title: '手机号码为空或者未满11位',
          icon: 'none'
        });
        return;
      }
      if (!verifyCode) {
        wx.showToast({
          title: '请输入验证码',
          icon: 'none'
        });
        return;
      }
      
      // 提交审核
      wx.showLoading({
        title: '提交中...'
      });
      
      console.log("住户信息表单",this.data.residentData);

      setTimeout(()=>{
        wx.hideLoading();
        wx.showToast({
          title: '提交成功',
          icon : 'success'
        })

        // 进入第三步
        this.setData({
          currentStep: 2
        });
      },2000)


      // 提交
      setTimeout(()=>{
        console.log("拿不到id",JSON.stringify(this.data.residentData));
        console.log(this.data.imageUrl);
        http.get('resident/resident/houseAudit',this.data.residentData)
    .then(resp=>{
      if(resp.data == 0){

        //判断数据是否存在

        http.post('residentHouseMiddle/residentHouseMiddle',{
          residentId:this.data.residentData.id,
          houseId:this.data.formData.houseId,
          ownerResidentId:this.data.residentData.relationToOwnerId,
        })
        .then(resp=>{
          if(resp.data==0){
              //审核通过
            this.setData({
              isFailed:false,
              currentStep:3
            })
            wx.showToast({
              title: '审核通过',
              icon : 'success',
            })


            //修改房屋的信息
            setTimeout(()=>{
              http.put('house/house',{
                id:this.data.formData.houseId,
                authenticationStatus:0,
                imageUrl:this.data.imageUrl,
                houseStatusId:this.data.formData.houseStatusId
              }).then(resp=>{
                wx.showToast({
                  title: '房屋认证成功',
                })
              })
            },1000)

          } else{
            //审核失败
            this.setData({
              isFailed:true,
              currentStep: 3
            })
            wx.showToast({
              title: '审核失败',
              icon : 'error',
            })


            //修改房屋的认证状态
            setTimeout(()=>{
              http.put('house/house',{
                id:this.data.formData.houseId,
                authenticationStatus:2,
                imageUrl:this.data.imageUrl
              }).then(resp=>{
                wx.showToast({
                  title: '房屋认证成功',
                })
              })
            },1000)

          }
      })
        .catch(err=>{
          console.log("无法绑定");
          wx.showToast({
            title: '绑定失败',
          })
        })
      }else{
        //审核失败
        this.setData({
          isFailed:true,
          currentStep: 3
        })
        wx.showToast({
          title: '审核失败',
          icon : 'error',
        })
      }
    })
    .catch(err=>{
      console.log("请求失败",err);
      wx.showToast({
        title: '请求发送失败',
      })
    })
      }, 5000);


      
    } else if (this.data.currentStep === 2) {
      wx.showLoading({
        title: '处理中...'
      });
      
      setTimeout(() => {
        wx.hideLoading();  
        // 进入第四步
        this.setData({
          currentStep: 3,
          isFailed: !isSuccess
        });
      }, 1500);
    }
  },

  // 第三步：物业审核相关方法
  // 修改信息
  editInfo() {
    // 返回第一步
    this.setData({
      currentStep: 0
    });
  },

  // 删除审核
  cancelReview() {
    wx.showModal({
      title: '提示',
      content: '确定要删除此房屋认证申请吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...'
          });
          
          // 模拟删除
          setTimeout(() => {
            wx.hideLoading();
            wx.navigateBack();
          }, 1500);
        }
      }
    });
  },

  // 第四步：认证成功相关方法
  // 返回首页
  returnToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 查看我的房屋
  viewMyHouse() {
    wx.navigateTo({
      url: '/mine/pages/my-house/my-house'
    });
  },

  // 第四步：认证失败相关方法
  // 联系客服
  contactService() {
    wx.showModal({
      title: '联系客服',
      content: '客服电话：400-123-4567\n工作时间：周一至周五 9:00-18:00',
      confirmText: '拨打电话',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '4001234567'
          });
        }
      }
    });
  },

  // 重新认证
  retryAuthentication() {
    // 返回第一步重新填写
    this.setData({
      currentStep: 0,
      isFailed: false
    });
  },


//查询小区列表
queryCommunity(){
  http.get('community/community/list')
  .then(resp=>{
    this.setData({
      communityList:resp.rows
    })
  })
  .catch(err=>{

  })
},
//查询楼座列表，根据小区id查询
queryBuilding(){
  http.get('building/building/list',
  {
    communityId:this.data.formData.communityId
  })
  .then(resp=>{
    wx.hideLoading();
    this.setData({
      buildingList:resp.rows
    })
  })
  .catch(err=>{
    console.log("请求失败",err);
  })
},

//查询房屋
queryHouse(){
  console.log("小区d",this.data.formData.communityId);
  console.log("楼房",this.data.formData.buildingId);
  http.get('house/house/list',{
    communityId:this.data.formData.communityId,
    buildingId:this.data.formData.buildingId
  }).then(resp=>{
    houseList:resp.rows
  })
},
//查询房屋状态
queryHouseStatus(){
  http.get('houseStatus/houseStatus/list').then(resp=>{
    this.setData({
      houseStatus:resp.rows
    })
  })
  .catch(err=>{
    console.log("请求失败",err);
  })
},

  //查询身份证类型
  queryIdType(){
    http.get('idCardType/idCardType/list')
    .then(resp=>{
      this.setData({
        idTypeList:resp.rows
      })
    })
    .catch(err=>{
      console.log("请求失败",err);
      wx.showToast({
        title: '获取数据失败',
        icon: "error"
      })
    })
  },
  //与业主的关系
  queryRelation(){
    http.get('ownerRelation/ownerRelation/list')
    .then(resp=>{
      this.setData({
        relationList:resp.rows
      })
    })
    .catch(err=>{
      console.log("请求失败",err);
      wx.showToast({
        title: '业主关系请求失败',
        icon: "error"
      })
    })
  },
  //提交审核
  commitAudit(){
    http.get('resident/resident/houseAudit',this.data.residentData)
    .then(resp=>{
      if(resp.data == 0){
        //审核通过
        this.setData({
          isFailed:true
        })
        wx.showToast({
          title: '审核通过',
          icon : 'success',
        })
      }else{
        //审核失败
        this.setData({
          isFailed:false
        })
        wx.showToast({
          title: '审核失败',
          icon : 'error',
        })
      }
    })
    .catch(err=>{
      console.log("请求失败",err);
      wx.showToast({
        title: '请求发送失败',
      })
    })
  }
})
